package service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

import messageControl.Message;
import messageControl.MessageDao;
import messageControl.MessageListView;
import util.mysqlUtil;

public class GetMessage {
	String tableName;
	public GetMessage(String tableName) {
		this.tableName = tableName;
	}
	private static final int MESSAGE_COUNT_PER_PAGE = 5;

	public MessageListView getMessageList(int pageNumber) throws ServiceException {
		Connection conn = null;
		int currentPageNumber = pageNumber;
		try {
			conn = mysqlUtil.getConn();
			MessageDao messageDao = new MessageDao(tableName);
			int messageTotalCount = messageDao.selectCount(conn);

			List<Message> messageList = null;
			int firstRow = 0;
			int endRow = 0;
			if (messageTotalCount > 0) {
				endRow = messageTotalCount - (pageNumber - 1) * MESSAGE_COUNT_PER_PAGE;
				firstRow = endRow - MESSAGE_COUNT_PER_PAGE + 1;
				messageList = messageDao.selectList(conn, firstRow, endRow);
			} else {
				currentPageNumber = 0;
				messageList = Collections.emptyList();
			}
			return new MessageListView(messageList,
					messageTotalCount, currentPageNumber,
					MESSAGE_COUNT_PER_PAGE, firstRow, endRow);
		} catch (SQLException e) {
			throw new ServiceException("메시지 목록 구하기 실패: "
					+ e.getMessage(), e);
		} finally {
			mysqlUtil.close(conn);
		}
	}
}